package com.common.controller;

import com.common.config.CommonApplicationConfig;
import com.common.enums.ApiResult;
import com.common.exception.ErrorException;
import com.common.model.SystemApplicationServiceModel;
import com.common.model.SystemApplicationWebModel;
import com.common.mysql.Where;
import com.common.sevice.SystemApplicationWebService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/v1/system-application-web")
public class SystemApplicationWebController extends Controller<String, SystemApplicationWebService, SystemApplicationWebModel> {

    @Autowired
    private CommonApplicationConfig config;


    /**
     * 树结构查询
     *
     * @param appId
     * @return
     */
    @GetMapping("/list")
    public ApiResult list(@RequestParam(required = false) String appId) {
        if (!StringUtils.hasText(appId)) {
            appId = config.getAppId();
            if (!StringUtils.hasText(appId)){
                throw new ErrorException("应用id不能为空");
            }
        }
        List<SystemApplicationWebModel> result = service.list(appId);
        return ApiResult.success(result);
    }


    /**
     * 复制
     * @param appId
     * @param id
     * @return
     */
    @PutMapping("/copy")
    public ApiResult copy(@RequestParam(required = false) String appId,
                          @RequestParam(required = false) String id) {
        if (!StringUtils.hasText(appId) || !StringUtils.hasText(id)){
            throw new ErrorException("必填项不能为空");
        }
        service.copy(appId, id);
        return ApiResult.success();
    }

    @Override
    public ApiResult delete(@RequestBody SystemApplicationWebModel model) {
        if (ObjectUtils.isEmpty(model.getId())){
            throw new ErrorException("主键信息不能为空！");
        }
        service.deleteChildren(model.getId());
        return ApiResult.success();
    }

    @Override
    public ApiResult add(@RequestBody SystemApplicationWebModel model) {
        String appId = model.getAppId();
        if (!StringUtils.hasText(appId)){
            throw new ErrorException("应用id不能为空！");
        }
        String code = model.getCode();
        SystemApplicationWebModel webModel = service.searchOne(Where.build().field("app_id").equal(appId)
                .and().field("type").notEqual("1")
                .and().field("code").equal(code)
                .and().field("del_flag").equal(0));
        if (!ObjectUtils.isEmpty(webModel)){
            throw new ErrorException("名称重复，添加失败");
        }
        return super.add(model);
    }
}
